﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SketchTour.Filters;
using System.Web.Security;

namespace SketchTour.Controllers.Security
{
    [InitializeSimpleMembership]
    public class RoleManagerController : Controller
    {
        #region View Role

        public ActionResult Index()
        {
            string[] model = Roles.GetAllRoles();
            return View(model);
        }

        #endregion View Role

        #region CreateRole

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(string name)
        {
            Roles.CreateRole(name);
            return RedirectToAction("Index");
        }

        #endregion

        #region Permission
        [Authorize(Roles = "Admin")]
        public ActionResult Permission()
        {
            string[] roles = Roles.GetAllRoles();
            return View(roles);
        }

        [HttpPost]
        [Authorize(Roles = "Admin")]
        public ActionResult Permission(string userName)
        {
            string[] oldRoles = Roles.GetRolesForUser(userName);
            if (oldRoles.Length > 0)
            {
                Roles.RemoveUserFromRoles(userName, oldRoles);
            }

            foreach (string role in Request.Form.Keys)
            {
                if (role.StartsWith("chkRole")) 
                {
                    string roleName = role.Substring(7);
                    Roles.AddUserToRole(userName, roleName);
                }
            }

            string[] roles = Roles.GetAllRoles();
            return View(roles);
        }

        #endregion
    }
}
